﻿using Avalonia.Media.Imaging;
using Bilibili.Common.Api;
using Bilibili.Common.Log;
using Bilibili.Model.User;
using Bilibili.WebClient;
using Bilibili.WebClient.Api;
using LibVLCSharp.Shared;
using PCLUntils;
using PCLUntils.Plantform;
using ReactiveUI;
using System;
using System.Diagnostics;
using System.IO;
using System.Reactive;
using System.Reflection;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Libs
{
    public sealed class StaticValue
    {
        private StaticValue() { }
        static StaticValue()
        {
            try
            {
                string libvlcDirectoryPath = string.Empty;
                if (PlantformUntils.System == Platforms.Windows)
                {
                    var archString = !PlantformUntils.IsArmArchitecture ? "win-x64" : "win-arm64";
                    libvlcDirectoryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location ?? Assembly.GetExecutingAssembly()?.Location), "libvlc", archString);
                }
                LogManager.Instance.LogInfo($"libvlc path: {libvlcDirectoryPath}");
                Core.Initialize(libvlcDirectoryPath);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("InitPlayer", ex);
            }
        }
        public const string WEB_NAME = "web";
        public static long CurrentUserId { get; set; }
        private static object HasInit { get; set; } = false;
        public static GeetestInfo GeetestData { get; set; }
        public static Random Radom { get; private set; }
        public static string CurrentUserName { get; set; }
        public static Bitmap CurrentUserIcon { get; set; }
        public static IApiClient ApiClient { get; private set; }
        public static ReactiveCommand<Unit, Unit> LoginEvent { get; set; }
        public static void Init()
        {
            Task.Factory.StartNew(async () =>
            {
                if (HasInit is bool value && value == false)
                {
                    HasInit = true;
                    Radom = new Random();
                    ApiClient = Current.Instance.ApiClient;
                    await EmoteClient.Instance.LoadCache();
                    using Process process = new Process();
                    process.StartInfo = new ProcessStartInfo
                    {
                        FileName = $"Service.Bilibili{(PlantformUntils.System == Platforms.Windows ? ".exe" : string.Empty)}",
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };
                    process.Start();
                }
            });
        }
        public static void Dispose()
        {
            try
            {
                ApiClient.Dispose();
                GC.Collect();
            }
            catch { }
        }
    }
}